package com.rio.volley;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.rio.core.L;
import com.rio.core.U;

/**
 * 
 * Volley中实现文件上传
 * 
 * <pre>
 * // 获取MultipartEntity对象
 * MultipartEntity multipartEntity = multipartRequest.getMultiPartEntity();
 * multipartEntity.addStringPart("content", "hello");
 * //
 * Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.thumb);
 * // bitmap参数
 * multipartEntity.addBinaryPart("images", bitmapToBytes(bitmap));
 * // 文件参数
 * multipartEntity.addFilePart("images", new File("storage/emulated/0/test.jpg"));
 * // 构建请求队列
 * RequestQueue queue = RequestQueue.newRequestQueue(Context);
 * // 将请求添加到队列中
 * queue.addRequest(multipartRequest);
 * 
 * 
 * </pre>
 * 
 * 
 * @author rio.lv
 * 
 * @param <T>
 */
public abstract class MultipartRequest<T> extends Request<T> {

	private MultipartEntity mMultiPartEntity;

	private final Listener<T> mListener;

	public MultipartRequest(int method, String url, MultipartEntity entity,
			Listener<T> listener, ErrorListener errorListener) {
		super(method, url, errorListener);
		this.mListener = listener;
		this.mMultiPartEntity = entity;
	}

	/**
	 * @return
	 */
	public MultipartEntity getMultiPartEntity() {
		return mMultiPartEntity;
	}

	@Override
	public byte[] getBody() throws AuthFailureError {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			// 将mMultiPartEntity中的参数写入到bos中
			mMultiPartEntity.writeTo(bos);
		} catch (IOException e) {
			L.e(e);
		}
		return bos.toByteArray();
	}

	@Override
	public String getBodyContentType() {
		if(mMultiPartEntity==null)return null;
		return mMultiPartEntity.getContentType().getValue();
	}

	@Override
	protected Response<T> parseNetworkResponse(NetworkResponse response) {
		try {
			String json = new String(response.data,
					HttpHeaderParser.parseCharset(response.headers));
			T result = executeResponse(json);
			return Response.success(result,
					HttpHeaderParser.parseCacheHeaders(response));
		} catch (Exception e) {
			return Response.error(new VolleyError(e));
		}
	}

	public abstract T executeResponse(String json) throws Exception;

	@Override
	protected void deliverResponse(T response) {
		mListener.onResponse(response);
	}

}
